<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="钱包地址" prop="walletAddress">
              <el-input v-model="queryParams.walletAddress" placeholder="请输入钱包地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="质押产品" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入质押产品" clearable @keyup.enter="handleQuery" />
            </el-form-item>
<!--            <el-form-item label="质押记录ID" prop="stakingId">-->
<!--              <el-input v-model="queryParams.stakingId" placeholder="请输入质押记录ID" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
<!--            <el-form-item label="返利日期" prop="rebateDate">-->
<!--              <el-date-picker clearable-->
<!--                              v-model="queryParams.rebateDate"-->
<!--                              type="date"-->
<!--                              value-format="YYYY-MM-DD"-->
<!--                              placeholder="请选择返利日期"-->
<!--              />-->
<!--            </el-form-item>-->
            <el-form-item label="返利日期" prop="rebateDate">
              <el-date-picker
                v-model="queryParams.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                :shortcuts="shortcuts"
                :clearable="true"
              />
            </el-form-item>
            <el-form-item label="收益类型" prop="rewardType">
              <el-select v-model="queryParams.rewardType" placeholder="请选择奖励类型" clearable >
                <el-option label="产品收益" :value="parseInt('1')"/>
                <el-option label="等级返利" :value="parseInt('2')"/>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable >
                <el-option v-for="dict in rebate_records_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" border :data="rebateRecordList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="center" />-->
<!--        <el-table-column label="记录ID" align="center" prop="id" v-if="true" />-->
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="质押产品" align="center" prop="productName" />
        <el-table-column label="钱包地址" align="center" prop="walletAddress" width="260" />
        <el-table-column label="返利金额(USDZ)" align="center" prop="rebateAmount" />
        <el-table-column label="收益类型" align="center" prop="rewardType">
          <template #default="scope">
            <el-tag>{{scope.row.rewardType == 1 ? "产品收益" : "等级返利"}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="计算基数(USDZ)" align="center" prop="baseAmount" />
        <el-table-column label="奖励比例" align="center" prop="rewardRate" />
        <el-table-column label="返利日期" align="center" prop="rebateDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.rebateDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="第几天" align="center" prop="dayNumber" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="rebate_records_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="说明" align="center" prop="remark" />
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--          <template #default="scope">-->
<!--            <el-tooltip content="修改" placement="top">-->
<!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:rebateRecord:edit']"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip content="删除" placement="top">-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:rebateRecord:remove']"></el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改返利记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="rebateRecordFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="质押记录ID" prop="stakingId">
          <el-input v-model="form.stakingId" placeholder="请输入质押记录ID" />
        </el-form-item>
        <el-form-item label="返利金额" prop="rebateAmount">
          <el-input v-model="form.rebateAmount" placeholder="请输入返利金额" />
        </el-form-item>
        <el-form-item label="返利日期" prop="rebateDate">
          <el-date-picker clearable
                          v-model="form.rebateDate"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择返利日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="第几天" prop="dayNumber">
          <el-input v-model="form.dayNumber" placeholder="请输入第几天" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in rebate_records_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计算基数" prop="baseAmount">
          <el-input v-model="form.baseAmount" placeholder="请输入计算基数" />
        </el-form-item>
        <el-form-item label="奖励比例" prop="rewardRate">
          <el-input v-model="form.rewardRate" placeholder="请输入奖励比例" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RebateRecord" lang="ts">
import { listRebateRecord, getRebateRecord, delRebateRecord, addRebateRecord, updateRebateRecord } from '@/api/business/rebateRecord';
import { RebateRecordVO, RebateRecordQuery, RebateRecordForm } from '@/api/business/rebateRecord/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { rebate_records_status } = toRefs<any>(proxy?.useDict('rebate_records_status'));

const rebateRecordList = ref<RebateRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const rebateRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RebateRecordForm = {
  id: undefined,
  userId: undefined,
  stakingId: undefined,
  rebateAmount: undefined,
  rebateDate: undefined,
  dayNumber: undefined,
  status: undefined,
  rewardType: undefined,
  baseAmount: undefined,
  rewardRate: undefined
}
const data = reactive<PageData<RebateRecordForm, RebateRecordQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    walletAddress: undefined,
    productName: undefined,
    stakingId: undefined,
    rebateAmount: undefined,
    rebateDate: undefined,
    dayNumber: undefined,
    status: undefined,
    rewardType: undefined,
    baseAmount: undefined,
    rewardRate: undefined,
    dateRange: [], // [startDate, endDate]
  },
  rules: {
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    rewardType: [
      { required: true, message: "奖励类型：1-产品收益，2-等级返利不能为空", trigger: "change" }
    ],
    baseAmount: [
      { required: true, message: "计算基数不能为空", trigger: "blur" }
    ],
    rewardRate: [
      { required: true, message: "奖励比例不能为空", trigger: "blur" }
    ]
  }
});

// 时间快捷选项（只包含日期）
const shortcuts = [
  {
    text: '今天',
    value: () => {
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    text: '昨天',
    value: () => {
      const start = new Date();
      start.setDate(start.getDate() - 1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setDate(end.getDate() - 1);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      const start = new Date();
      start.setDate(start.getDate() - 6);
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      const start = new Date();
      start.setDate(start.getDate() - 29);
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    text: '本月',
    value: () => {
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    text: '上个月',
    value: () => {
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setMonth(end.getMonth() - 1);
      end.setDate(0);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  }
];
const { queryParams, form, rules } = toRefs(data);

/** 查询返利记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRebateRecord(queryParams.value);
  rebateRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  rebateRecordFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.dateRange = [];
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: RebateRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加返利记录";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: RebateRecordVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getRebateRecord(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改返利记录";
}

/** 提交按钮 */
const submitForm = () => {
  rebateRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRebateRecord(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addRebateRecord(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: RebateRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除返利记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delRebateRecord(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('business/rebateRecord/export', {
    ...queryParams.value
  }, `rebateRecord_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
